package com.xsq;

import android.app.Application;
import android.content.Context;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;

import com.xsq.utils.SharedPreferencesUtils;
import com.xsq.utils.ToastUtil;
import org.xutils.x;

public class BaseApplication extends Application {

    private volatile static BaseApplication instance;
    private SharedPreferencesUtils spUtils;

    public static BaseApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        x.Ext.init(this);
        x.Ext.setDebug(true);
        ToastUtil.init(this);
        instance = this;
        spUtils = new SharedPreferencesUtils(this, "XSQ");
    }

    public void hideKeyboard(IBinder token) {
        ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(token, 0);
    }

    public int getFlowId() {
        String flowIds = spUtils.getObject("FLOW_ID", String.class);
        if(TextUtils.isEmpty(flowIds)) {
            flowIds = "0";
        }
        int flowId = Integer.valueOf(flowIds);
        flowId = flowId + 1;
        spUtils.setObject("FLOW_ID", String.valueOf(flowId));
        return flowId;
    }

    public boolean hasConfiged() {
        return (!TextUtils.isEmpty(getBaseUrl())) && (!TextUtils.isEmpty(getWinId()))
                && (getPriceType() != 0);
    }

    public void setConfig(String baseUrl, String winId, int type, String autoPrice) {
        if(!TextUtils.isEmpty(baseUrl)) {
            spUtils.setObject("BASE_URL", baseUrl);
        }
        /*if(!TextUtils.isEmpty(merId)) {
            spUtils.setObject("MER_ID", merId);
        }*/
        if(!TextUtils.isEmpty(winId)) {
            spUtils.setObject("WIN_ID", winId);
        }
        if(!TextUtils.isEmpty(autoPrice)) {
            spUtils.setObject("AUTO_PRICE", autoPrice);
        }
        spUtils.setObject("PRICE_TYPE", String.valueOf(type));
    }

    /**
     * @return 获取配置的地址
     */
    public String getBaseUrl() {
        String baseUrl = spUtils.getObject("BASE_URL", String.class);
        return baseUrl;
    }

    /**
     * @return 获取配置的商户号
     */
    public String getMerId() {
        String merId = spUtils.getObject("MER_ID", String.class);
        return merId;
    }

    /**
     * @return 获取配置的窗口号
     */
    public String getWinId() {
        String winId = spUtils.getObject("WIN_ID", String.class);
        return winId;
    }

    /**
     * @return 获取配置的扣款方式
     */
    public int getPriceType() {
        String priceType = spUtils.getObject("PRICE_TYPE", String.class);
        if(TextUtils.isEmpty(priceType)) {
            return 0;
        }
        return Integer.valueOf(priceType);
    }

    /**
     * @return 获取配置的自动扣款金额
     */
    public String getAutoPrice() {
        String autoPrice = spUtils.getObject("AUTO_PRICE", String.class);
        return autoPrice;
    }

}
